package com.zhilianbao.leyaogo.alipay;

import android.app.Activity;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.bql.utils.AsyncTaskUtils;
import com.zhilianbao.leyaogo.constants.PayConfig;

import java.util.Map;

/**
 * Author: hcy
 * Description:支付宝支付工具类
 * Created: 2016/10/26 09:27
 */
public class AliPayUtil {
    private String rsaPrivate;// 商户私钥，pkcs8格式
    private String paitenrId;// 商户PID
    private String seller;// 商户收款账号
    private String tradeNo;// 订单号
    private String productName;// 商品名称
    private String productDesc;// 商品描述
    private String notify_url;// 回调地址
    private float productFee;// 商品花费

    public Map<String, String> aliPayResult;
    public String payParam;
    private Activity activity;

    private IPayCallBack mIPayCallBack;

    public void setPayCallBack(IPayCallBack mIPayCallBack) {
        this.mIPayCallBack = mIPayCallBack;
    }


    private AliPayUtil(Activity activity, String rsaPrivate, String paitenrId, String productName, String productDesc,
                       String seller, String tradeNo, String notify_url, float productFee) {
        this.rsaPrivate = rsaPrivate;
        this.paitenrId = paitenrId;
        this.seller = seller;
        this.tradeNo = tradeNo;
        this.productName = productName;
        productDesc = (productDesc == null) ? "" : (productDesc.length() > 30 ? productDesc.substring(0, 30) : productDesc);
        this.productDesc = productDesc;
        this.notify_url = notify_url;
        this.productFee = productFee;
        this.activity = activity;
    }

    private AliPayUtil(Activity activity, String payParam) {
        this.activity = activity;
        this.payParam = payParam;
    }

    public static AliPayUtil createInstance(Activity activity, String rsaPrivate, String paitenrId, String productName, String productDesc, String seller, String tradeNo, String notify_url, float productFee) {
        return new AliPayUtil(activity, rsaPrivate, paitenrId, productName, productDesc, seller, tradeNo, notify_url, productFee);
    }

    public static AliPayUtil createInstance(Activity activity, String payParam) {
        return new AliPayUtil(activity, payParam);
    }

    /**
     * 开启支付任务
     */
    public void startToPay() {
        //		new AliPayTask().execute(this);
        //开启支付异步任务
        AsyncTaskUtils.exe(new AsyncTask<AliPayUtil, Void, AliPayUtil>() {
            @Override
            protected AliPayUtil doInBackground(AliPayUtil... params) {
                AliPayUtil aliPayUnit = params[0];
                String payInfo = aliPayUnit.payParam;
                PayTask aliPay = new PayTask(aliPayUnit.activity);
                // 调用支付接口，获取支付结果
                aliPayUnit.aliPayResult = aliPay.payV2(payInfo, true);
                return aliPayUnit;
            }

            @Override
            protected void onPostExecute(AliPayUtil aliPayUtil) {
                super.onPostExecute(aliPayUtil);
                aliPayUtil.activity = null;
                aliPayUtil.processAliPayResult(aliPayUtil.aliPayResult);
            }
        }, this);
    }

    public Activity getActivity() {
        return activity;
    }

    /**
     * 创建订单信息，并签名,这里是demo
     */
    public String getOrderInfo() {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(PayConfig.ALI_APP_ID);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, rsaPrivate);
        String orderInfo = orderParam + "&" + sign;
        return orderInfo;
    }

    /**
     * 处理支付结果
     *
     * @param result
     */
    public void processAliPayResult(Map<String, String> result) {
        if (mIPayCallBack == null)
            return;
        PayResult payResult = new PayResult(result);

        /**
         对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
         */
        //		String resultInfo = payResult.getResult();// 同步返回需要验证的信息
        String resultStatus = payResult.getResultStatus();
        // 判断resultStatus 为9000则代表支付成功
        if (TextUtils.equals(resultStatus, "9000")) {
            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
            mIPayCallBack.paySuccess();
        } else {
            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
            // 判断resultStatus 为非“9000”则代表可能支付失败
            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            if (TextUtils.equals(resultStatus, "8000")) {
                mIPayCallBack.payOnWaitForConfirm();
            }
            //用户中途取消
            else if (TextUtils.equals(resultStatus, "6001")) {
                mIPayCallBack.userCanceled();
            } else {
                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                mIPayCallBack.payFailed();
            }
        }
    }


    /**
     * 支付任务
     */
    private static class AliPayTask extends AsyncTask<AliPayUtil, Void, AliPayUtil> {

        @Override
        protected AliPayUtil doInBackground(AliPayUtil... params) {
            AliPayUtil aliPayUnit = params[0];
            String payInfo = aliPayUnit.payParam;
            PayTask aliPay = new PayTask(aliPayUnit.activity);
            // 调用支付接口，获取支付结果
            aliPayUnit.aliPayResult = aliPay.payV2(payInfo, true);
            return aliPayUnit;
        }

        @Override
        protected void onPostExecute(AliPayUtil result) {
            super.onPostExecute(result);
            result.activity = null;
            result.processAliPayResult(result.aliPayResult);
        }
    }

}
